//
// Created by yyancy on 2019/10/27.
//
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <asm/errno.h>
#include <errno.h>

#define MAXLINE 100

void err_quit(char *str);

ssize_t
Readline(int fd, void *ptr, size_t maxlen);

ssize_t
readlines(int fd, void *vptr, size_t maxlen);


void
str_cli(FILE *fp, int sockfd) {
    char sendline[MAXLINE], recvline[MAXLINE];

    // for (int i = 0; i < MAXLINE; ++i) {
    //     recvline[i] = 0;
    //     sendline[i] = 0;
    // }

    while (fgets(sendline, MAXLINE, fp) != NULL) {
        write(sockfd, sendline, strlen(sendline));
        if (Readline(sockfd, recvline, MAXLINE) == 0)
            err_quit("str_cli: server terminated prematurely");

        fprintf(stderr, "yancy received: %s ", recvline);
    }
}


void err_quit(char *str) {
    fprintf(stderr, "%s\n", str);
    exit(1);
}

void err_sys(char *s) {
    fprintf(stderr, "%s\n", s);
    exit(1);
}


/* PAINFULLY SLOW VERSION -- example only */
ssize_t
readlines(int fd, void *vptr, size_t maxlen) {
    ssize_t n, rc;
    char c, *ptr;

    ptr = vptr;
    for (n = 1; n < maxlen; n++) {
        again:
        if ((rc = read(fd, &c, 1)) == 1) {
            *ptr++ = c;
            if (c == '\n')
                break;    /* newline is stored, like fgets() */
        } else if (rc == 0) {
            *ptr = 0;
            return (n - 1);    /* EOF, n - 1 bytes were read */
        } else {
            if (errno == EINTR)
                goto again;
            return (-1);        /* error, errno set by read() */
        }
    }

    *ptr = 0;    /* null terminate like fgets() */
    return (n);
}

/* end readline */

ssize_t
Readline(int fd, void *ptr, size_t maxlen) {
    ssize_t n;

    if ((n = readlines(fd, ptr, maxlen)) < 0)
        err_sys("readline error");
    return (n);
}



